Javascript Trim LTrim and RTrim Functions
Description
This set of Javascript functions trim or remove whitespace from the ends of strings. These functions can be stand-alone or attached as methods of the String object. They can left trim, right trim, or trim from both sides of the string. Rather than using a clumsy loop, they use simple, elegant regular expressions. The functions are granted to the public domain.
Javascript Trim Member Functions
Use the code below to make trim a method of all Strings. These are useful to place in a global Javascript file included by all your pages.
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}
// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+myString.trim()+"*");
alert("*"+myString.ltrim()+"*");
alert("*"+myString.rtrim()+"*");
Javascript Trim Stand-Alone Functions
If you prefer not to modify the string prototype, then you can use the stand-alone functions below.
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}
// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");
Example
Type in the box below and you will see the trimmed output dynamically. You must enter spaces before and after the string to see a difference. All whitespace is removed, including tabs and line feeds.
Compatibility
The functions above use regular expressions, which are compatible with Javascript 1.2+ or JScript 3.0+. All modern (version 4+) browsers will support this. If you require functions for older versions of Javascript back to version 1.0, try the functions below adapted from the Javascript FAQ 4.16. These strip the following, standard whitespace characters: space, tab, line feed, carriage return, and form feed. The IsWhitespace function checks if a character is whitespace.
function ltrim(str) {
for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
return str.substring(k, str.length);
}
function rtrim(str) {
for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
return str.substring(0,j+1);
}
function trim(str) {
return ltrim(rtrim(str));
}
function isWhitespace(charToCheck) {
var whitespaceChars = " \t\n\r\f";
return (whitespaceChars.indexOf(charToCheck) != -1);
}
Disclaimer: This content is provided as-is. The information may be incorrect.